import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import dptoken from '@/utils/dptoken'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  document.title = to.meta.title == '金融' ? '供应链金融系统' : getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  /**
   * 判断是否有token
    * 如果有就判断是否为登录链接
    *  如果是就跳转到根路由
    *  如果不是就判断是否有动态路由
    *    如果没有就获取动态路由并跳转到目标页面
    *    如果有就跳转到目标页面
    *       判断是否需要模拟登陆
    * 如果没有
    *  判断白名单
    *  判断是否有passport
    *  就跳转到登录并设置redirect
    * 
   */
  if (hasToken) {
    // if (to.path === '/login') {
    //   next({ path: '/' })
    //   NProgress.done()
    // } else {
      if (store.getters.roles.length === 0) {
        genaraterroute(next, to)
      } else {
        tonext(next, to)
      }
    // }
  } else {
    //没有token
    //判断passport
    if (to.query && to.query.passport) {
      store.dispatch('user/passport', to.query.passport).then(res => {
        //设置token
        // if (true) {
        // }
        genaraterroute(next, to)
      })
    }else{
      if (whiteList.indexOf(to.path) !== -1) {
        // in the free login whitelist, go directly
        next()
      } else {
        // other pages that do not have permission to access are redirected to the login page.
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  }
})

function genaraterroute(next, to) {
  store.dispatch('user/getInfo').then(res => { // 拉取用户信息
    let menus = res.menus;
    let username = res.username;
    store.dispatch('GenerateRoutes', { menus, username }).then(() => { // 生成可访问的路由表
      router.addRoutes(store.getters.addRouters); // 动态添加可访问路由表
      next({ ...to, replace: true })
      tonext(next, to)
    })
  }).catch((err) => {
    store.dispatch('user/FedLogOut').then(() => {
      Message.error(err || 'Verification failed, please login again')
      next({ path: '/' })
    })
  })
}

function tonext(next, to) {
  if (['/zhengzhou_n','/tongyong'].indexOf(to.path) != -1) {
    store.state.daping.type = to.meta.name
    dptoken().then(res => {
      if (res.code == 200) {
        next()
      }else{
        Message.error("后台接口错误")
        next({ path: '/404' })
      }
    })
  }else if (to.path === '/login') {
    next({ path: '/' })
    NProgress.done()
  } else{
    next()
  }
}

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
